package cn.qidisoft.edu.hzjt.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.qidisoft.core.common.pagination.PaginationBean;

/**
 * 分页标签类
 * 
 * @author kevin
 * @version 1.0
 */
@SuppressWarnings("rawtypes")
public class PageTag extends TagSupport {

    /**
     * 
     */
    private static final long   serialVersionUID        = 5778259163449567591L;

    Logger                      logger                  = LoggerFactory.getLogger(this.getClass());

    private String              uid;

    private PaginationBean      pageHolder;

    private String              append                  = null;

    private String              requestURI              = null;

    private String              userclass;

    private String              pageSizeclass;

    private String              currPageSizeclass;

    private boolean             viewpagesize            = true;

    private boolean             viewtotalcount          = true;

    private static final int    CONNUM                  = 5;

    private static final String style                   = "background: #ffffff;color: #000000;border:0px";

    private String              currentPageSeletedStyle = "background: #ffffff;color: #FF7800;border:0px;padding:2px 8px 2px 8px;";

    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            String strHTML = getHTMLString();
            out.print(strHTML);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return SKIP_BODY;
    }

    public String test() {
        return getHTMLString();
    }

    private String getHTMLString() {
        StringBuffer sb = new StringBuffer();
        if (pageHolder.getTotalRecords() != 0) {
            addJavaScript(sb);
            sb.append("<form name=\"thisform\" id=\"" + uid
                      + "\" onsubmit=\"return false;\" style=\"margin: 0px; padding: 0px\">");
            sb.append("<ul>");
            if (viewtotalcount)
                setTotalRecordsTitle(pageHolder, sb);
            sb.append("\n");
            setFirstPageHTML(pageHolder, sb, style);
            sb.append("\n");
            setPrePageHTML(pageHolder, sb, style);
            sb.append("\n");
            setPreOtherPageHTML(sb, pageHolder);
            sb.append("\n");
            setForEachPageNumHTML(pageHolder, sb, null);
            sb.append("\n");
            setNextOtherPageHTML(sb, pageHolder, style);
            sb.append("\n");
            setNextPageHTML(pageHolder, sb, style);
            sb.append("\n");
            setLastPageHTML(pageHolder, sb, style);
            sb.append("\n");
            setForwardPage(pageHolder, sb, style);
            sb.append("\n");
            if (viewpagesize)
                setPageSize(sb, style);
            sb.append("\n");
            sb.append("</ul>");
            sb.append("</form>");
        }
        return sb.toString();
    }

    private void setPageSize(StringBuffer sb, String style) {
        setBeginLIHTML(sb, style);
        int[] pageSize = new int[] { 10, 20, 40, 50 };
        sb.append("每页显示条数：");
        sb.append(
            "<select name=\"pageSize\" style=\"whith:30px\" id=\"pageSize\" onchange=\"javascript:var _p=$(this).val();window.location.href ='"
                  + requestURI + "?pageSize='+_p+'&currentPage=" + pageHolder.getCurrentPage()
                  + "&maxCount=" + pageHolder.getTotalRecords() + "&" + append + "'\">");
        for (int i = 0; i < pageSize.length; i++) {
            if (getPageHolder().getPageSize() == pageSize[i]) {
                sb.append("<option value=\"" + pageSize[i] + "\" selected=\"selected\">");
            } else {
                sb.append("<option value=\"" + pageSize[i] + "\">");
            }
            sb.append(pageSize[i]);
            sb.append("条" + "</option>");
        }

        sb.append("</select>");
        setEndLIHTML(sb);
    }

    private void addJavaScript(StringBuffer sb) {
        sb.append(
            "<script type=\"text/javascript\">	function isDigit(s)	{	var patrn=/^[0-9]{1,20}$/;	if (!patrn.exec(s)){ return false;}else{return true}	}	function isNumberFloat(inputString)	{	 return (!isNaN(parseInt(inputString))) ? true : false;}function goPage(frm,appparam){	var pageNo = frm.gotoPage.value;if(isDigit(pageNo) && isNumberFloat(pageNo)){if (pageNo<1){pageNo=1;}else if (pageNo>"
                  + pageHolder.getTotalPage() + "){pageNo=" + pageHolder.getTotalPage()
                  + ";}window.location.href = \"" + requestURI
                  + "?currentPage=\"+pageNo+\"&maxCount=" + pageHolder.getTotalRecords()
                  + "&pageSize=" + pageHolder.getPageSize() + "&" + append + "\"+appparam"
                  + ";		}else{alert(\"" + "请输入整数，范围不要超过999999999"
                  + "\");}}function keycheck(frm){  if (window.event.keyCode == 13)  {goPage(frm,'');}}</script>");

    }

    /**
     * 设置跳转页面
     * 
     * @param pageHolder
     * @param sb
     * @param style
     */

    private void setForwardPage(PaginationBean pageHolder, StringBuffer sb, String style) {
        setBeginLIHTML(sb, style);
        // sb
        // .append("<input name=\"gotoPage\" onKeydown=\"keycheck(this.form)\"
        // id=\"gotoPage\" type=\"text\" size=\"9\" maxlength=\"9\"
        // title=\"请输入要跳转的页码,只能是正整数.\">&nbsp;&nbsp;<input type=\"button\"
        // name=\"gotoButton\" value=\"GO\" id=\"gotoButton\"
        // onClick=\"goPage(this.form,'')\">");
        sb.append(
            "显示：<select name=\"gotoPage\" id=\"gotoPage\" onchange=\"goPage(this.form,'');\">");
        for (int i = 1; i <= pageHolder.getTotalPage(); i++) {
            if (pageHolder.getCurrentPage() == i) {
                sb.append("<option value=\"" + i + "\" selected=\"selected\">");
            } else {
                sb.append("<option value=\"" + i + "\">");
            }

            sb.append("第" + i + "页");
            sb.append("</option>");
        }
        sb.append("</select>&nbsp;&nbsp;&nbsp;&nbsp;");
        // sb.append("&nbsp;&nbsp;<input type=\"button\" name=\"gotoButton\"
        // value=\"GO\" id=\"gotoButton\" onClick=\"goPage(this.form,'')\">");
        setEndLIHTML(sb);
    }

    private void setTotalRecordsTitle(PaginationBean pageHolder, StringBuffer sb) {
        setBeginLIHTML(sb, style);
        sb.append("共" + pageHolder.getTotalRecords() + "条记录&nbsp;&nbsp;&nbsp;&nbsp;");

        sb.append("显示");
        sb.append(pageHolder.getCurrentPage() * pageHolder.getPageSize()
                  - (pageHolder.getPageSize() - 1));
        sb.append("到");
        // sb.append(pageHolder.getTotalPage());
        if (pageHolder.getCurrentPage() == pageHolder.getTotalPage()) {
            sb.append(pageHolder.getTotalRecords());
        } else {
            sb.append(pageHolder.getCurrentPage() * pageHolder.getPageSize());
        }

        sb.append("条记录&nbsp;&nbsp;");

        setEndLIHTML(sb);
    }

    /**
     * 设置上页
     * 
     * @param page
     * @param sb
     */
    private void setPrePageHTML(PaginationBean page, StringBuffer sb, String style) {
        if (page.getCurrentPage() > 1) {
            getHTMLString(sb, page.getCurrentPage() - 1, isAppend(), "[上一页]", style);
        }

    }

    private boolean isAppend() {
        boolean bool = false;
        if (this.append != null || !append.trim().equals("")) {
            bool = true;
        }
        return bool;
    }

    /**
     * 设置下页
     * 
     * @param page
     * @param sb
     */
    private void setNextPageHTML(PaginationBean page, StringBuffer sb, String style) {
        if (page.getCurrentPage() < page.getTotalPage()) {
            getHTMLString(sb, page.getCurrentPage() + 1, isAppend(), "[下一页]", style);
        }
    }

    /**
     * 设置其他隐藏的页
     * 
     * @param sb
     */
    private void setPreOtherPageHTML(StringBuffer sb, PaginationBean page) {
        if (page.getCurrentPage() >= CONNUM) {
            setBeginLIHTML(sb, style);
            sb.append("...");
            setEndLIHTML(sb);
        }
    }

    private void setNextOtherPageHTML(StringBuffer sb, PaginationBean page, String style) {
        if (page.getTotalPage() - page.getCurrentPage() >= CONNUM) {
            setBeginLIHTML(sb, style);
            sb.append("...");
            setEndLIHTML(sb);
        }
    }

    /**
     * 设置可连接的页
     * 
     * @param page
     * @param sb
     */
    private void setForEachPageNumHTML(PaginationBean page, StringBuffer sb, String style) {
        int begin = getBeginNum(page);
        int end = getEndNum(page);
        for (int i = begin; i <= end; i++) {
            if (i == page.getCurrentPage()) {
                getCurrentHTMLString(sb, i);
            } else {
                getHTMLString(sb, i, isAppend(), i + "", style);
            }
        }
    }

    private int getBeginNum(PaginationBean page) {
        int begin = 0;
        int currentPage = page.getCurrentPage();
        int totalPage = page.getTotalPage();
        if (currentPage < CONNUM) {
            begin = 1;
        } else if (currentPage % CONNUM == 0) {
            if (totalPage - CONNUM >= 2) {
                if (currentPage >= totalPage) {
                    begin = totalPage - 4;
                } else {
                    begin = currentPage - 1;
                }
            } else {
                begin = 1;
            }
        } else {
            if ((currentPage - 1) % CONNUM == 0) {
                begin = currentPage - 1;
            } else if ((currentPage - 2) % CONNUM == 0) {
                begin = currentPage - 1;
            } else if ((currentPage - 3) % CONNUM == 0) {
                begin = currentPage - 2;
            } else if ((currentPage - 4) % CONNUM == 0) {
                begin = currentPage - 3;
            }
        }
        return begin;
    }

    private int getEndNum(PaginationBean page) {
        int end = 0;
        int currentPage = page.getCurrentPage();
        int totalPage = page.getTotalPage();
        if (currentPage < CONNUM && totalPage > CONNUM) {
            end = CONNUM;
        } else if (currentPage % CONNUM == 0) {
            if (totalPage - CONNUM <= 2) {
                end = page.getTotalPage();
            } else {
                if (currentPage >= totalPage) {
                    end = totalPage;
                } else {
                    end = currentPage + 4;
                    end = getEndNum(end, totalPage);
                }
            }
        } else {
            if ((currentPage - 1) % CONNUM == 0) {
                end = currentPage + 4;
                end = getEndNum(end, totalPage);
            } else if ((currentPage - 2) % CONNUM == 0) {
                end = currentPage + 3;
                end = getEndNum(end, totalPage);
            } else if ((currentPage - 3) % CONNUM == 0) {
                end = currentPage + 2;
                end = getEndNum(end, totalPage);
            } else if ((currentPage - 4) % CONNUM == 0) {
                end = currentPage + 1;
                end = getEndNum(end, totalPage);
            }
        }
        return end;
    }

    private int getEndNum(int end, int totalPage) {
        if (end > totalPage) {
            return totalPage;
        }
        return end;
    }

    /**
     * 第一页
     * 
     * @param page
     * @param sb
     */
    private void setFirstPageHTML(PaginationBean page, StringBuffer sb, String style) {
        if (page.getCurrentPage() >= CONNUM) {
            getHTMLString(sb, 1, isAppend(), "[首页]", style);
        }
    }

    /**
     * 最后一页
     * 
     * @param page
     * @param sb
     */
    private void setLastPageHTML(PaginationBean page, StringBuffer sb, String style) {
        if (page.getTotalPage() - page.getCurrentPage() >= CONNUM) {
            getHTMLString(sb, page.getTotalPage(), isAppend(), "[页末]", style);
        }
    }

    private void getHTMLString(StringBuffer sb, int pageNum, boolean bool, String title,
                               String style) {
        setPreLink(sb, style);

        if (bool) {
            sb.append("?");
            sb.append("currentPage=" + pageNum + "&pageSize=" + pageHolder.getPageSize()
                      + "&maxCount=" + pageHolder.getTotalRecords());
            sb.append("&");
            sb.append(append);
        }
        setNextLink(sb, title);
    }

    private void getCurrentHTMLString(StringBuffer sb, int pageNum) {
        setBeginLIHTML(sb, currentPageSeletedStyle);
        sb.append(pageNum);
        setEndLIHTML(sb);
    }

    private void setPreLink(StringBuffer sb, String style) {
        setBeginLIHTML(sb, style);
        sb.append("<a href=\"");
        sb.append(requestURI);

    }

    private void setBeginLIHTML(StringBuffer sb, String style) {
        if (style == null) {
            sb.append("<li>");
        } else {
            sb.append("<li style=\"" + style + "\">");
        }

    }

    private void setEndLIHTML(StringBuffer sb) {
        sb.append("</li>");
    }

    private void setNextLink(StringBuffer sb, String title) {
        sb.append("\">");

        sb.append(title);
        sb.append("</a>");
        setEndLIHTML(sb);

    }

    /**
     * @return the append
     */
    public String getAppend() {
        return append;
    }

    /**
     * @param append the append to set
     */
    public void setAppend(String append) {
        this.append = append;
    }

    /**
     * @return the pageHolder
     */
    public PaginationBean getPageHolder() {
        return pageHolder;
    }

    /**
     * @param pageHolder the pageHolder to set
     */
    public void setPageHolder(PaginationBean pageHolder) {
        this.pageHolder = pageHolder;
    }

    /**
     * @return the requestURI
     */
    public String getRequestURI() {
        return requestURI;
    }

    /**
     * @param requestURI the requestURI to set
     */
    public void setRequestURI(String requestURI) {
        this.requestURI = requestURI;
    }

    /**
     * @return the uid
     */
    public String getUid() {
        return uid;
    }

    /**
     * @param uid the uid to set
     */
    public void setUid(String uid) {
        this.uid = uid;
    }

    /**
     * @return the userclass
     */
    public String getUserclass() {
        return userclass;
    }

    /**
     * @param userclass the userclass to set
     */
    public void setUserclass(String userclass) {
        this.userclass = userclass;
    }

    public static void main(String[] args) {
        PageTag pt = new PageTag();
        PaginationBean pageHolder = new PaginationBean();
        pageHolder.setCurrentPage(15);
        pageHolder.setTotalRecords(192);
        pageHolder.setPageSize(10);
        pageHolder.init();

        pt.setPageHolder(pageHolder);
        pt.setRequestURI("aaa.do");
        pt.setAppend("affasfaf=aaa");

        System.out.println(pt.test());
    }

    /**
     * @return the currPageSizeclass
     */
    public String getCurrPageSizeclass() {
        return currPageSizeclass;
    }

    /**
     * @param currPageSizeclass the currPageSizeclass to set
     */
    public void setCurrPageSizeclass(String currPageSizeclass) {
        this.currPageSizeclass = currPageSizeclass;
    }

    /**
     * @return the pageSizeclass
     */
    public String getPageSizeclass() {
        return pageSizeclass;
    }

    /**
     * @param pageSizeclass the pageSizeclass to set
     */
    public void setPageSizeclass(String pageSizeclass) {
        this.pageSizeclass = pageSizeclass;
    }

    /**
     * @return the viewpagesize
     */
    public boolean isViewpagesize() {
        return viewpagesize;
    }

    /**
     * @param viewpagesize the viewpagesize to set
     */
    public void setViewpagesize(boolean viewpagesize) {
        this.viewpagesize = viewpagesize;
    }

    /**
     * @return the viewtotalcount
     */
    public boolean isViewtotalcount() {
        return viewtotalcount;
    }

    /**
     * @param viewtotalcount the viewtotalcount to set
     */
    public void setViewtotalcount(boolean viewtotalcount) {
        this.viewtotalcount = viewtotalcount;
    }

    public String getCurrentPageSeletedStyle() {
        return currentPageSeletedStyle;
    }

    public void setCurrentPageSeletedStyle(String currentPageSeletedStyle) {
        this.currentPageSeletedStyle = currentPageSeletedStyle;
    }

}
